import { useRef } from 'react';
import dayjs from 'dayjs';
import { Space, message } from 'antd';
import {
  deleteArticleApi,
  findArticleListByLikeRecord,
  findArticleListByLookRecord,
} from '@/services/articles';
import type { ActionType } from '@ant-design/pro-components';
import { ProList } from '@ant-design/pro-components';
import useRequest from '@ahooksjs/use-request';
import articleEnum from '@/constant/article';
import 'dayjs/locale/zh-cn';
import locale from 'antd/lib/date-picker/locale/zh_CN';

import styles from './index.less';

type Props = {};

const Index: React.FC<Props> = () => {
  const actionRef = useRef<ActionType>(null);
  const { run: deleteArticleRun } = useRequest(deleteArticleApi, {
    manual: true,
    onSuccess(data) {
      const { code, message: errorMessage } = data;
      if (code === 200) {
        message.success('删除成功');
        actionRef.current?.reload();
      } else {
        message.error(errorMessage);
      }
    },
  });

  const tableAlertOptionRender = ({
    selectedRows,
    onCleanSelected,
  }: COMMON.TableAlert<ARTICLEAPI.ARTICLE>) => {
    const articleIds = selectedRows.map((item) => item.articleId);
    return (
      <Space size={24}>
        <span>
          <a
            style={{ marginInlineStart: 8, color: 'red' }}
            onClick={() => deleteArticleRun({ articleIds })}
          >
            删除已选择
          </a>
          <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
            取消已选择
          </a>
        </span>
      </Space>
    );
  };
  return (
    <div className={styles.likeWrapper}>
      <ProList<
        ARTICLEAPI.ARTICLE & {
          articleLikeRecord: ARTICLEAPI.ArticleLikeRecord;
        }
      >
        rowSelection={{}}
        actionRef={actionRef}
        tableAlertOptionRender={tableAlertOptionRender}
        search={{}}
        rowKey="articleId"
        request={async (params = {}) => {
          const startTime = params?.createTime?.[0];
          const endTime = params?.createTime?.[1];
          let res = null;
          params.createTime = null;
          params.author = params?.user?.nickname;
          params.user = null;
          if (params.status === articleEnum.historyRecordType.footprint.key) {
            res = await findArticleListByLookRecord({
              ...params,
              startTime,
              endTime,
            });
          } else {
            res = await findArticleListByLikeRecord({
              ...params,
              startTime,
              endTime,
            });
          }
          if (res.code === 200) {
            return {
              data: res.data.records,
              total: res.data.total,
            };
          } else {
            message.error(res.message);
            return [];
          }
        }}
        pagination={{
          pageSize: 10,
        }}
        metas={{
          title: {
            dataIndex: ['user', 'nickname'],
            title: '用户名称',
            render: (_, row) => {
              const {
                user: { nickname } = {},
                articleLikeRecord: { createTime } = {},
                articleLookRecord: { createTime: articleLookRecordCreateTime } = {},
              } = row;
              console.log(row);
              return (
                <div>
                  {nickname}
                  <span style={{ color: '#aaa', marginLeft: '10px' }}>
                    {dayjs(createTime || articleLookRecordCreateTime).format('YYYY-MM-DD HH:mm:ss')}
                  </span>
                </div>
              );
            },
          },
          avatar: {
            dataIndex: ['user', 'headPortrait'],
            search: false,
          },
          description: {
            dataIndex: 'articleTitle',
            search: false,
          },
          createTime: {
            valueType: 'dateTimeRange',
            title: '记录时间',
            search: true,
            fieldProps: {
              locale,
            },
          },
          actions: {
            render: (_, row) => [
              <a style={{ color: 'red' }} rel="noopener noreferrer" key="link">
                删除
              </a>,
              <a
                href={`/article/view/${row.articleId}`}
                target="_blank"
                rel="noopener noreferrer"
                key="view"
              >
                查看
              </a>,
            ],
            search: false,
          },
          status: {
            // 自己扩展的字段，主要用于筛选，不在列表中显示
            title: '状态',
            valueType: 'select',
            formItemProps: {
              initialValue: 'footprint',
            },
            fieldProps: {
              allowClear: false,
            },
            valueEnum: articleEnum.historyRecordType.original,
          },
        }}
      />
      ;
    </div>
  );
};
export default Index;
